#!/bin/sh

# TODO: support config locations:
# ./.piku-server
# ~/.piku-server
# git config --get remote.piku.url
# git config --get remote.paas.url

remote=`git config --get remote.piku.url`
remote=${remote:-"${PIKU_SERVER}:${PIKU_APP}"}

out() { printf "%s\n" "$*" >&2; }

out "Piku remote operator."

if [ "$remote" = "" ]
then
  out
  out "Error: no piku server configured."
  out "Use PIKU_SERVER=piku@MYSERVER.NET or configure a git remote called 'piku'."
  out
else
  server=`echo "$remote" | cut -f1 -d":" 2>/dev/null`
  app=`echo "$remote" | cut -f2 -d":" 2>/dev/null`
  # gather SSH flags
  while [ "${1#\-}"x != "${1}x" ];
  do
    sshflags="${sshflags} ${1}"
    shift
  done
  # check the Piku command to be run
  cmd="$1"
  out "Server: $server"
  out "App: $app"
  out
  case "$cmd" in
    "")
      ssh ${sshflags} "$server" "$@" | grep -v "INTERNAL"
      ;;
    apps|setup|setup:ssh)
      ssh ${sshflags} "$server" "$@"
      ;;
    shell)
      ssh -t "$server" run "$app" bash
      ;;
    *)
      shift # remove cmd arg
      ssh ${sshflags} "$server" "$cmd" "$app" "$@"
      ;;
  esac
fi
